package com.xiongtian.springframework.beans.factory.support;

import com.xiongtian.springframework.beans.BeansException;
import com.xiongtian.springframework.beans.factory.ConfigurableListableBeanFactory;
import com.xiongtian.springframework.beans.factory.config.BeanDefinition;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author: xiongtian
 * @CreateTime: 2025-03-25  10:43
 * @Version: 1.0
 * @Description: 默认的Bean工厂类
 * 实现了获取BeanDefinition的方法
 * 实现了注册BeanDefinition的方法
 */

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements BeanDefinitionRegistry, ConfigurableListableBeanFactory {

    /**
     * Bean定义映射
     */
    private final Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();

    @Override
    public BeanDefinition getBeanDefinition(String beanName) {
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if (null == beanDefinition) {
            throw new RuntimeException("No bean named " + beanName + " is defined");
        }
        return beanDefinition;
    }

    /**
     * 注册Bean定义
     *
     * @param beanName       Bean名称
     * @param beanDefinition Bean定义
     */
    @Override
    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
        beanDefinitionMap.put(beanName, beanDefinition);
    }

    /**
     * 是否包含指定名称的Bean定义
     *
     * @param beanName Bean名称
     * @return 是否包含
     */
    public boolean containsBeanDefinition(String beanName) {
        return beanDefinitionMap.containsKey(beanName);
    }

    /**
     * 根据类型获取Bean
     *
     * @param type Bean类型
     * @return Bean实例
     * @throws BeansException 异常
     */
    @Override
    public <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException {
        Map<String, T> result = new HashMap<>();
        beanDefinitionMap.forEach((beanName, beanDefinition) -> {
            Class beanClass = beanDefinition.getBeanClass();
            if (type.isAssignableFrom(beanClass)) {
                result.put(beanName, (T) getBean(beanName));
            }
        });
        return result;
    }

    /**
     * 获取所有Bean名称
     * 返回注册表中所有的Bean名称
     *
     * @return Bean名称数组
     */
    @Override
    public String[] getBeanDefinitionNames() {
        return beanDefinitionMap.keySet().toArray(new String[0]);
    }


    /**
     * 实例化所有非懒加载的单例Bean
     * 遍历BeanDefinitionMap，调用getBean方法实例化所有非懒加载的单例Bean
     * 这样，在容器启动时，所有的单例Bean都会被实例化
     * 注意：这里只是实例化，并没有初始化，初始化是在getBean方法中调用initializeBean方法实现的
     *
     * @throws BeansException 异常
     */
    @Override
    public void preInstantiateSingletons() throws BeansException {
        beanDefinitionMap.keySet().forEach(this::getBean);
    }


    /**
     * 获取指定类型的Bean
     *
     * @param requiredType Bean类型
     * @param <T>          Bean类型
     * @return Bean实例
     * @throws BeansException 异常
     */
    @Override
    public <T> T getBean(Class<T> requiredType) throws BeansException {
        List<String> beanNames = new ArrayList<>();
        for (Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()) {
            Class beanClass = entry.getValue().getBeanClass();
            if (requiredType.isAssignableFrom(beanClass)) {
                beanNames.add(entry.getKey());
            }
        }
        if (1 == beanNames.size()) {
            return getBean(beanNames.get(0), requiredType);
        }

        throw new BeansException(requiredType + "expected single bean but found " + beanNames.size() + ": " + beanNames);
    }
}
